import 'package:flutter/material.dart';
import 'dart:ui';

import 'package:flutter/services.dart';

void main() => runApp(MyApp(pageIndex: window.defaultRouteName));

class MyApp extends StatefulWidget {
  final String pageIndex;
  const MyApp({Key key, this.pageIndex}) : super(key: key);
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  //1、初始化方法通道参数name与OC保持一致
  final MethodChannel _pageChannel = MethodChannel("page_method");
  //2、持续消息发送与接收，OC对应的name参数需要和当前name保持一致
  final BasicMessageChannel _messageChannel = BasicMessageChannel("messageChannel", StandardMessageCodec());
  String _method = 'one';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //发送消息要页面
    _messageChannel.send("page?");
    //监听OC发送的消息
    _pageChannel.setMethodCallHandler((MethodCall call){
      _method = call.method;
      setState(() {});
    });
    //发送一条消息
    _messageChannel.send("I am hibo");
    //接收消息
    _messageChannel.setMessageHandler((message){
      print(message);
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
          primarySwatch: Colors.blue,
          backgroundColor: Colors.white
      ),
      color: Colors.yellow,
      home: rootPage(_method),
    );
  }

  Widget rootPage(String method){
    print(method);
    switch (method) {
      case 'one':
        return Scaffold(
            backgroundColor: Colors.blue,
            body:  GestureDetector(
              onTap: (){
                //像OC发送消息，方法名+参数
                _pageChannel.invokeMapMethod('page','arg1');
              },
              child: Center(
                child: Container(
                  child: Text("混合开发one，点击返回",style: TextStyle(fontSize: 30),),
                ),
              ),
            )
        );
        break;
      case 'two':
        return Scaffold(
            backgroundColor: Colors.yellow,
            body: GestureDetector(
              onTap: (){
                //调用OC原生方法方法名、参数，one_page字符要和OC中监听的方法名相同
                _pageChannel.invokeMapMethod('page','arg1');
              },
              child: Center(
                child: Container(
                  child: Text("混合开发two，点击返回",style: TextStyle(fontSize: 30),),
                ),
              ),
            )
        );
        break;
      default:
        return Scaffold(
            backgroundColor: Colors.blue,
            body: Center(
              child: Container(
                child: Text("default",style: TextStyle(fontSize: 30),),
              ),
            )
        );
        break;
    }
  }
}




